#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import render_template, redirect, url_for, abort, flash, request, \
    current_app, make_response
from flask.ext.login import login_required, current_user
from . import application
from .. import db
from ..models import User, Tomcat, Nginx, Host, Project, Vhost
from .forms import TomcatForm, NginxForm, VhostForm, ProjectForm, EditTomcatForm
import time
import os


@application.route('/')
def index():
    return redirect(url_for('.tomcatlist'))


@application.route("/tomcatlist")
def tomcatlist():
    tomcatList = Tomcat.query.all()
    print tomcatList
    if tomcatList:
        return render_template('application/list.html', tomcatList=tomcatList)
    else:
        return redirect(request.args.get('next') or url_for('.index'))


@application.route('/addtomcat', methods=['GET', 'POST'])
def add_tomcat():
    form = TomcatForm()
    if form.validate_on_submit():
        host = Host.query.filter_by(id=form.host.data).first()
        tomcat = Tomcat(
            app_name=form.app_name.data,
            app_cmd_start=form.app_cmd_start.data,
            app_cmd_stop=form.app_cmd_stop.data,
            app_comments=form.app_comments.data,
            host=Host.query.get(form.host.data)
        )
        tomcat.http_port = form.http_port.data
        tomcat.ajp_port = form.ajp_port.data
        if tomcat.installTomcat():
            tmpfile = tomcat.getConfigFile()
            tomcat.setPorts(tmpfile)

        # for i in range(5):
        #     if tomcat.isExist():
        #         print i
        #         tmpfile = tomcat.getConfigFile()
        #         tomcat.setPorts(tmpfile)
        #         break
        #     else:
        #         time.sleep(1)

        db.session.add(tomcat)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))
    return render_template('application/addtomcat.html', form=form)


@application.route('/edittomcat/<int:id>', methods=['GET', 'POST'])
def edit_tomcat(id):
    tomcat = Tomcat.query.get_or_404(id)
    form = EditTomcatForm()
    if form.validate_on_submit():
        if tomcat.isExist('/usr/local/tomcat_' + form.app_name.data):
            flash("There were already exist Tomcat at %s" %
                  tomcat.host.hostname)
            return render_template('application/addtomcat.html', form=form)

        old_app_dir = tomcat.app_dir
        tomcat.app_name = form.app_name.data
        tomcat.app_dir = os.path.dirname(
            tomcat.app_dir) + "/tomcat_" + tomcat.app_name
        tomcat.app_cmd_start = form.app_cmd_start.data
        tomcat.app_cmd_stop = form.app_cmd_stop.data
        tomcat.app_comments = form.app_comments.data
        tomcat.host = Host.query.get(form.host.data)
        tomcat.http_port = form.http_port.data
        tomcat.ajp_port = form.ajp_port.data

        tname = os.path.dirname(tomcat.app_dir) + "/tomcat_" + tomcat.app_name
        if not tomcat.moveTomcat(old_app_dir, tname):
            flash('rename the %s, %s failed' %
                  (os.path.basename(old_app_dir), tomcat.app_name))
            return render_template('application/addtomcat.html', form=form)

        for i in range(5):
            if tomcat.isExist("/usr/local/tomcat_" + tomcat.app_name):
                print i
                tmpfile = tomcat.getConfigFile()
                tomcat.setPorts(tmpfile)
                break
            else:
                time.sleep(1)
        db.session.add(tomcat)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))

    form.app_id.data = tomcat.id
    form.app_name.data = tomcat.app_name
    form.app_cmd_start.data = tomcat.app_cmd_start
    form.app_cmd_stop.data = tomcat.app_cmd_stop
    form.app_comments.data = tomcat.app_comments
    form.host.data = Host.query.get(tomcat.host_id).id
    form.http_port.data = tomcat.http_port
    form.ajp_port.data = tomcat.ajp_port
    return render_template('application/addtomcat.html', form=form)


@application.route('/addvhost', methods=['GET', 'POST'])
def add_vhost():
    form = VhostForm()
    if form.validate_on_submit():
        # nginx = Nginx.query.filter_by(id=form.nginx.data).first()
        vhost = Vhost(
            conf_name=form.conf_name.data,
            nginx=Nginx.query.get(form.nginx.data)
        )
        db.session.add(vhost)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))
    return render_template('application/addvhost.html', form=form)


@application.route('/editvhost/<int:id>', methods=['GET', 'POST'])
def edit_vhost(id):
    vhost = Vhost.query.get_or_404(id)
    form = VhostForm()
    if form.validate_on_submit():
        # nginx = Nginx.query.filter_by(id=form.nginx.data).first()
        vhost.conf_name = form.conf_name.data
        vhost.nginx = Nginx.query.get(form.nginx.data)

        db.session.add(vhost)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))
    form.conf_name.data = vhost.conf_name
    form.nginx.data = vhost.nginx.id
    return render_template('application/addvhost.html', form=form)


@application.route('/addnginx', methods=['GET', 'POST'])
def add_nginx():
    form = NginxForm()
    if form.validate_on_submit():
        nginx = Nginx()
        nginx.app_name = form.app_name.data
        nginx.app_dir = form.app_dir.data
        nginx.app_cmd_start = form.app_cmd_start.data
        nginx.app_cmd_stop = form.app_cmd_stop.data
        nginx.app_comments = form.app_comments.data
        nginx.host = Host.query.get(form.host.data)

        db.session.add(nginx)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))
    return render_template('application/addnginx.html', form=form)


@application.route('/editnginx/<int:id>', methods=['GET', 'POST'])
def edit_nginx(id):
    nginx = Nginx.query.get_or_404(id)
    form = NginxForm()
    if form.validate_on_submit():
        nginx.app_name = form.app_name.data
        nginx.app_dir = form.app_dir.data
        nginx.app_cmd_start = form.app_cmd_start.data
        nginx.app_cmd_stop = form.app_cmd_stop.data
        nginx.app_comments = form.app_comments.data
        nginx.host = Host.query.get(form.host.data)

        db.session.add(nginx)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))
    form.app_name.data = nginx.app_name
    form.app_dir.data = nginx.app_dir
    form.app_cmd_start.data = nginx.app_cmd_start
    form.app_cmd_stop.data = nginx.app_cmd_stop
    form.app_comments.data = nginx.app_comments
    form.host.data = nginx.host.id
    return render_template('application/addnginx.html', form=form)


@application.route('/addproject', methods=['GET', 'POST'])
def add_project():
    form = ProjectForm()
    if form.validate_on_submit():
        project = Project()
        project.name = form.name.data
        project.domain = form.domain.data
        for i in form.tomcat.data:
            project.tomcat.append(Tomcat.query.get(i))

        for i in form.nginx.data:
            project.nginx.append(Nginx.query.get(i))

        project.scmUrl = form.scmUrl.data
        project.srcDir = form.srcDir.data

        db.session.add(project)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))
    return render_template('application/addproject.html', form=form)


@application.route('/editproject/<int:id>', methods=['GET', 'POST'])
def edit_project(id):
    project = Project.query.get_or_404(id)
    form = ProjectForm()
    if form.validate_on_submit():
        project.name = form.name.data
        project.domain = form.domain.data
        print form.tomcat.data
        for i in form.tomcat.data:
            project.tomcat.append(Tomcat.query.get(i))
        for i in form.nginx.data:
            project.nginx.append(Nginx.query.get(i))

        project.scmUrl = form.scmUrl.data
        project.srcDir = form.srcDir.data

        db.session.add(project)
        db.session.commit()
        return redirect(request.args.get('next') or url_for('.index'))
    form.name.data = project.name
    form.domain.data = project.domain
    form.tomcat.data = (t.id for t in project.tomcat)
    form.nginx.data = (n.id for n in project.nginx)
    form.scmUrl.data = project.scmUrl
    form.srcDir.data = project.srcDir
    return render_template('application/addproject.html', form=form)


@application.route("/view/<category>/<id>")
def view(category, id):
    pass


@application.route("/view/<category>/<id>")
def delete(category, id):
    pass
